/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package edu.utx.spot.timesync;

import com.sun.spot.peripheral.Spot;
import com.sun.spot.peripheral.ISpot;
import com.sun.spot.peripheral.PIOPin;
import com.sun.squawk.Address;
import com.sun.squawk.Unsafe;
import com.sun.squawk.VM;
import com.sun.squawk.vm.ChannelConstants;

/**
 *
 */
public class SystemTimerSyncClock implements ISyncClock {
    
    private ISpot theSpot;
    private PIOPin sfd_pin; // start of frame delimiter pin
    private Address addressOfLastDeviceInterruptTime;

    final long systemOffsetMS;
    long offset;
    long rate;

    public SystemTimerSyncClock() {

        this.theSpot = Spot.getInstance();
        this.sfd_pin = theSpot.getSpotPins().getCC2420_SFD_Pin();
        this.addressOfLastDeviceInterruptTime = Address.fromPrimitive(VM.execSyncIO(ChannelConstants.GET_LAST_DEVICE_INTERRUPT_TIME_ADDR, 0));

        this.systemOffsetMS = System.currentTimeMillis();
        this.offset = 0;
        this.rate = 1000;

    }

    //
    // ISyncClock
    //
    public long currentTimeMillis() {
        return currentTimeMicros() / 1000;
    }
    
    public long currentTimeMicros() {
        return (System.currentTimeMillis() - systemOffsetMS) * 1000;
        // (Spot.getInstance().getSystemTicks() / ISpot.SYSTEM_TICKER_TICKS_PER_MILLISECOND);
    }

    // adjustment
    public void setClockOffset(long offset) {
        this.offset = offset;
    }

    public void setClockRate(long rate) {

    }
    
    public long sfdTimestampTX() {
        return currentTimeMicros();
    }

    public long sfdTimestampRX() {
        final long sysTime = Unsafe.getLong(addressOfLastDeviceInterruptTime, 0);
        return (sysTime - systemOffsetMS) * 1000;
    }

	public boolean isSfdHigh() {
		return sfd_pin.isHigh();
	}
	
	//
	// IDriver
 	//
	public void setUp() {
        sfd_pin.claim();
        sfd_pin.openForInput();
	}
	
	public boolean tearDown() {
		sfd_pin.release();
		return true;
	}
	
	public void shutDown() {
	}
	
    public String getDriverName() {
        return "SystemTimerSyncClock";
    }
}
